<template>
  <div id="selector">
    <div id="header">
      <md-icon class="back_btn" name="snyc_nav_fh" @click.native="Cancel"></md-icon>
      <div class="middle">
        <div :class="isCity?'btn_selected left':'btn_outline left'" @click="cityMode">城市</div>
        <div :class="isCity?'btn_outline right':'btn_selected right'" @click="airStationMode">机场</div>
      </div>
    </div>
    <div id="searcher">
      <md-input-item type="text" v-model="searchValue" class="searcher-input" ref="searcher-input" :placeholder="isCity?hintString:'请输入机场'">
        <md-icon class="sousuo_icon" name="sousuo" slot="left"></md-icon>
        <md-icon name="clear_icon" slot="right" v-show="searchValue!=''" @click="clearSearchValue"></md-icon>
      </md-input-item>
      <!-- <div class="searcher-btn" @click="cancelSearch" v-show="searching">取消</div> -->
    </div>
    <md-scroll-view
      id="city-box"
      ref="scrollView"
      :scrolling-x="false"
      :bouncing="false"
      :auto-reflow="true"
      @scroll="$_onScroll"
      v-if="isCity"
      v-show="searchValue==''"
    >
      <div id="currentLocation" v-if="getCurrentLocation.provinceName" v-show="isStart" @click="currentLocationClick">当前定位城市：{{getCurrentLocation.provinceName}}</div>
      <div ref="hotCitys" class="hot-citys scroll-view-list scroll-view-category" v-if="isStart&&hotCitys.length>0">
        <div class="letter scroll-view-category-title">★ 热门城市</div>
        <ul>
          <li v-for="(city, $c) in hotCitys" :key="$c" @click="hotCitySubmit(city)">{{city.name}}</li>
        </ul>
      </div>
      <div v-for="(item, $index) in isStart ? getSortedStartCity : getSortedEndCity" :key="$index" class="scroll-view-list scroll-view-category">
        <div class="letter scroll-view-category-title" :ref="item.letter">{{item.letter}}</div>
        <div class="city-name" v-for="(city, $c) in item.data" :key="$c" @click="submit(city)">{{isStart ? city.start_route : city.end_route}}</div>
      </div>
    </md-scroll-view>
    <md-scroll-view
      id="city-box"
      ref="airScrollView"
      :scrolling-x="false"
      :bouncing="false"
      :auto-reflow="true"
      @scroll="$_onScroll"
      v-if="!isCity"
      v-show="searchValue==''"
    >
      <div v-for="(item, $index) in isStart ? sortedStartAirStations : sortedEndAirStations" :key="$index" class="scroll-view-list scroll-view-category">
        <div class="letter scroll-view-category-title" :ref="item.letter">{{item.letter}}</div>
        <div class="city-name" v-for="(city, $c) in item.data" :key="$c" @click="submit(city)">{{city.stationName}}</div>
      </div>
      <div class="no-result-view" v-show="!hasAirStationList">
        <md-icon name="yhq_kb" class="no-air-station-icon"></md-icon>
        <div class="text">{{noAirStationHintString}}</div>
      </div>
    </md-scroll-view>
    <md-scroll-view id="city-box" :scrolling-x="false" :bouncing="false" :auto-reflow="true" v-show="searchValue!=''">
      <div class="scroll-view-list" v-show="searchResultList.length>0" v-if="isCity">
        <div class="gaps"></div>
        <div class="city-name" v-for="(city, $c) in searchResultList" :key="$c" @click="submit(city)">{{isStart ? city.start_route : city.end_route}}</div>
      </div>
      <div class="scroll-view-list" v-show="searchResultList.length>0" v-if="!isCity">
        <div class="gaps"></div>
        <div class="city-name" v-for="(city, $c) in searchResultList" :key="$c" @click="submit(city)">{{city.stationName}}</div>
      </div>
      <div class="no-result-view" v-show="searchResultList.length<=0">
        <md-icon name="tishi" class="icon"></md-icon>
        <div class="text">暂无结果，换地方试试吧</div>
      </div>
    </md-scroll-view>
    <div v-if="activeBlockIndex != ''" v-show="searchValue == ''&&scrollY>scrollYOffset" class="scroll-view-striky-title">{{ activeBlockIndex }}</div>
    <letter-field v-show="searchValue == ''&&isCity" id="letter-field" :value="isStart?getSortedStartCity:getSortedEndCity" @change="scrollToLetter"></letter-field>
    <letter-field v-show="searchValue == ''&&!isCity" id="letter-field" :value="isStart?sortedStartAirStations:sortedEndAirStations" @change="scrollToLetter"></letter-field>
  </div>
</template>

<script>
/**
 * TODO 需要测试此模块是否会出现丢失城市的问题
 */
import '@/assets/svgs/snyc_nav_fh.svg';
import '@/assets/svgs/sousuo.svg';
import '@/assets/svgs/tishi.svg';
import '@/assets/svgs/yhq_kb.svg';
import '@/assets/svgs/clear_icon.svg';
import { mapGetters } from 'vuex';
import { GET_START_CITYS, GET_END_CITYS } from '@/store/actions.types';
import {
  SET_START_CITY_OBJ,
  SET_END_CITY_OBJ,
  SET_PIN_START_INFO,
  SET_PIN_END_INFO,
  SET_BAO_START_INFO,
  SET_BAO_END_INFO
} from '@/store/mutations.types';
import { InputItem, Field, FieldItem, Button, Icon, ScrollView, ScrollViewRefresh, ScrollViewMore } from 'mand-mobile';
import LetterField from './LetterField';
const PinyinEngine = require('pinyin-engine');
var pinyinEngine = null;
export default {
  name: 'city-selector',
  components: {
    [InputItem.name]: InputItem,
    [Field.name]: Field,
    [Button.name]: Button,
    [Icon.name]: Icon,
    [FieldItem.name]: FieldItem,
    [ScrollView.name]: ScrollView,
    [ScrollViewRefresh.name]: ScrollViewRefresh,
    [ScrollViewMore.name]: ScrollViewMore,
    [LetterField.name]: LetterField
  },
  data() {
    return {
      isStart: true,
      searchValue: '',
      searchResultList: [],
      dimensions: [],
      scrollY: 0,
      isCity: true,
      searching: false,
      scrollYOffset: 58
    };
  },
  methods: {
    $_initScrollBlock() {
      const blocks = this.$el.querySelectorAll('.scroll-view-category');
      let offset = 0;
      Array.prototype.slice.call(blocks).forEach((block, index) => {
        const innerHeight = block.clientHeight;
        this.$set(this.dimensions, index, [offset, offset + innerHeight]);
        offset += innerHeight;
      });
    },
    $_onScroll({ scrollTop }) {
      this.scrollY = scrollTop;
    },
    scrollToLetter(letter) {
      if (this.isCity) {
        this.$refs.scrollView.scrollTo(0, this.$refs[letter][0].offsetTop, true);
      } else {
        this.$refs.airScrollView.scrollTo(0, this.$refs[letter][0].offsetTop, true);
      }
    },
    clearSearchValue() {
      this.searchValue = '';
    },
    Cancel() {
      this.$router.go(-1);
    },
    currentLocationClick() {
      console.log(this.getCurrentLocation.provinceName);
      if (this.isStart) {
        let obj = {
          start_route: this.getCurrentLocation.provinceName,
          type: '1'
        };
        this.$store.commit(SET_START_CITY_OBJ, obj);
        this.$router.go(-1);
      }
    },
    submit(item) {
      this.$store.commit(this.isStart ? SET_START_CITY_OBJ : SET_END_CITY_OBJ, item);
      if (item.type === '2') {
        let info = {
          stationName: item.stationName,
          position: item.position,
          coordinate: item.coordinate.split(','),
          routeStationId: item.routeStationId
        };
        if (this.isStart) {
          this.$store.commit(SET_BAO_START_INFO, info);
        } else {
          this.$store.commit(SET_BAO_END_INFO, info);
        }
      }
      this.$router.go(-1);
    },
    hotCitySubmit(city) {
      let startObj = {
        start_route: city.name,
        type: '1'
      };
      this.$store.commit(SET_START_CITY_OBJ, startObj);
      this.$router.go(-1);
    },
    cityMode() {
      this.isCity = true;
      pinyinEngine = new PinyinEngine(
        this.isStart ? this.getStartCityList : this.getEndCityList,
        this.isStart ? 'start_route' : 'end_route'
      );
    },
    airStationMode() {
      this.isCity = false;
      if (this.isStart) {
        this.$store.dispatch('getStartAirStations').then(() => {
          console.log(this.sortedStartAirStations);
        });
      } else {
        this.$store.dispatch('getEndAirStations');
      }
      pinyinEngine = new PinyinEngine(this.isStart ? this.startAirStations : this.endAirStations, 'stationName');
    },
    onSearcherFocus() {
      this.searching = true;
    },
    cancelSearch() {
      this.searching = false;
      this.searchValue = '';
    }
  },
  created() {
    console.log('开始获取城市列表');
    this.isStart = this.$route.params.isStart;
    this.$store.dispatch(this.isStart ? GET_START_CITYS : GET_END_CITYS).then(() => {
      pinyinEngine = new PinyinEngine(
        this.isStart ? this.getStartCityList : this.getEndCityList,
        this.isStart ? 'start_route' : 'end_route'
      );
      this.$_initScrollBlock();
    });
    if (this.isStart) {
      console.log('获取推荐城市列表');
      this.$store.dispatch('getHotCitys').then(() => {
        this.scrollYOffset = this.$refs.hotCitys.clientHeight + 58;
      });
    }
  },
  computed: {
    activeBlockIndex() {
      let activeIndex = '';
      this.dimensions.forEach((dimension, index) => {
        if (this.scrollY >= dimension[0] && this.scrollY <= dimension[1]) {
          let word = this.isStart ? this.getSortedStartCity[index] : this.getSortedEndCity[index];
          activeIndex = word.letter;
        }
      });
      return activeIndex;
    },
    hintString() {
      return this.isStart ? '请输入出发城市' : '请输入目的地城市';
    },
    noAirStationHintString() {
      let str = '';
      if (this.isStart) {
        str = '机场线路未开通';
      } else {
        str = '起点城市未开通机场线路';
      }
      return str;
    },
    hasAirStationList() {
      let result = false;
      if (this.isStart) {
        if (this.startAirStations.length > 0) {
          result = true;
        } else {
          result = false;
        }
      } else {
        if (this.endAirStations.length > 0) {
          result = true;
        } else {
          result = false;
        }
      }
      return result;
    },
    ...mapGetters([
      'getCurrentLocation',
      'getSortedStartCity',
      'getSortedEndCity',
      'getStartCityList',
      'getEndCityList',
      'startAirStations',
      'sortedStartAirStations',
      'endAirStations',
      'sortedEndAirStations',
      'hotCitys'
    ])
  },
  watch: {
    searchValue(newvalue, oldvalue) {
      if (pinyinEngine) {
        this.searchResultList = pinyinEngine.query(newvalue);
      }
    }
  }
};
</script>

<style lang="stylus" scoped>
header_btn() {
  padding: 8px 30px;
  font-size: 30px;
  border: 1px solid color-primary;
}

#selector {
  background-color: color-primary-background;
  height: 100vh;

  #header {
    width: 100vw;
    height: 88px;
    background-color: #F8F8F8;

    .back_btn {
      float: left;
      width: 22px;
      height: 38px;
      margin-top: 25px;
      margin-left: 30px;
    }

    .middle {
      display: flex;
      flex-direction: row;
      justify-content: center;
      align-items: center;
      height: 88px;
      margin-right: 52px;

      .btn_outline {
        header_btn();
        color: color-primary;
      }

      .btn_selected {
        header_btn();
        background-color: color-primary;
        color: #fff;
      }

      .left {
        border-radius: 6px 0px 0px 6px;
      }

      .right {
        border-radius: 0px 6px 6px 0px;
      }
    }
  }

  #searcher {
    background-color: #F8F8F8;
    font-size: 28px;
    height: 88px;
    padding-left: 30px;
    padding-right: 30px;
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;

    .sousuo_icon {
      width: 30px;
      height: 30px;
    }

    .searcher-input {
      border: 0px;
      outline: none;
      width: 80%;
      background-color: transparent;
    }

    .searcher-btn {
      color: #888888;
      padding-left: 20px;
    }
  }

  #currentLocation {
    background-color: #fff;
    height: 88px;
    font-size: 28px;
    line-height: 88px;
    padding-left: 30px;
  }

  #city-box {
    height: calc(100vh - 196px);
    margin-top: 20px;
    background-color: #EFEFEF;

    .scroll-view-list {
      font-size: 28px;

      .letter {
        background-color: color-primary-background;
        padding: 30px;
        color: color-text-caption;
        width: 100vw;
      }

      .city-name {
        background-color: #fff;
        border-bottom: 1px solid #E0E0E0;
        padding: 30px;
      }

      .gaps {
        background-color: color-primary-background;
        height: 20px;
      }
    }

    .hot-citys {
      ul {
        display: flex;
        flex-flow: row wrap;
        padding: 30px 26px;
        background-color: #fff;

        li {
          font-size: 28px;
          line-height: 48px;
          text-align: center;
          border: 1px solid #E0E0E0;
          padding: 10px 14px;
          border-radius: 4px;
          width: 180px;
          margin: 5px 10px;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }
      }
    }

    .no-result-view {
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      margin-top: 200px;

      .icon {
        width: 80px;
        height: 80px;
        margin-bottom: 36px;
      }

      .no-air-station-icon {
        width: 280px;
        height: 160px;
        margin-bottom: 36px;
      }

      .text {
        font-size: 28px;
        color: rgba(102, 102, 102, 1);
        line-height: 40px;
      }
    }
  }

  #letter-field {
    height: 100vh;
    bottom: 0px;
  }

  .scroll-view-striky-title {
    position: absolute;
    top: 176px;
    left: 0;
    right: 0;
    background-color: color-primary-background;
    padding: 30px;
    color: color-text-caption;
    width: 100vw;
  }
}
</style>
